﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Text.RegularExpressions;

namespace NoORM.Core.DbDialect
{
    public class SqlDialect : IDbDialect
    {
        public string BuildParameterName(string parameterName)
        {
            return "@"+parameterName;
        }

        public string CreateParameterName(string parameterName)
        {
            return "@" + parameterName;
        }

        public string DeleteFrom()
        {
            return "";
        }

        public string WrapFieldName(string tableOrFieldName)
        {
            return "[" + tableOrFieldName + "]";
        }

        public string GetPageSql(string sql, string orderby, int pageSize, int pageIndex)
        {
            if (string.IsNullOrEmpty(orderby))
            {
                orderby = "getdate()";
            }
            else
            {
                string[] fields = orderby.Split(',');
                foreach(string item in fields)
                {
                    string fieldName = item.Split(' ')[0];
                    Regex reg = new Regex($@"\b{fieldName}\b");
                    orderby=reg.Replace(orderby, this.WrapFieldName(fieldName));
                }
            }
            long firstRow = pageIndex * pageSize;
            long endRow = (pageIndex + 1) * pageSize;
            sql = @$"
SELECT * FROM (
	SELECT ROW_NUMBER() OVER (ORDER BY {orderby}) RowNumber,* FROM
		({sql}) as TEMP1
) TEMP2
WHERE RowNumber>{firstRow} AND RowNumber<={endRow}";
            return sql;
        }
    }
}
